#!/usr/bin/env python
#-*-coding:utf-8-*-

# 'whyname.py' helps you to know the name policy of the host
# Copyright (C) 2010 F&J <f ampersend j dot gmail dot com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


################################################################################
# DOCS
################################################################################

"""'whyname.py' helps you to know the name policy of the host"""


################################################################################
# IMPORTS
################################################################################

import platform
import sys
import os


################################################################################
# META
################################################################################

__prj__ = "whyname.py"
__version__ = "0.2"
__author__ = "F&J"
__since__ = "0.1"
__date__ = "2010"
__license__ = "gpl3"
__copyright__ = """%s  Copyright (C) %s %s
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions; for details see LICENSE.txt.""" % (__prj__, __date__,
                                                             __author__)


################################################################################
# CONSTANTS
################################################################################

_OS_NAME, _HOSTNAME = platform.uname()[:2]


################################################################################
# CLASSES
################################################################################

class WhynameAppError(BaseException):

    def __init__(self, msg, code):
        """Crea una nueva instancia de WhynameError

        @param msg: Mensaje de la exeption
        @param code: codigo de error para retornar al sistema operativo

        """
        self.msg = msg
        self.code = code
        super(WhynameAppError, self).__init__()

    def __str__(self):
        # cuando se hace 'str(instancia)' se llama a este metodo
        return self.msg


################################################################################
# FUNCTIONS
################################################################################

def set_policy(policy, output_path):
    pf = open(output_path, "w")
    pf.write(policy)
    pf.close()


################################################################################
# MAIN
################################################################################

if __name__ == "__main__":
    
    import optparse
    
    output_path = ("c:\\windows\\system32\\"
                if _OS_NAME == "Windows" else r"/etc/") + "whyname.cfg"
    
    opt_parser = optparse.OptionParser("usage: %s [option] [arg]\n\n%s\n\n%s"
                                       % (__prj__, __doc__, __copyright__),
                                       version=__version__)
                                    
    opt_parser.add_option("-f", "--file", action="store", type="string",
                           dest="filename",
                           help="set the hostname policy from the file",
                           metavar="FILE")
                           
    opt_parser.add_option("-p", "--policy", action="store", type="string",
                           dest="policy",
                           help="set the hostname policy",
                           metavar="POLICY")
    try:
        options, args = opt_parser.parse_args()
        msg = ""
        if args:
            msg = "Unknow argument"
            if len(args) > 1:
                msg += "s %s" % ",".join([str(a) for a in args])
            else:
                msg += args[0]
            raise WhynameAppError(msg, 1)
        elif options.policy and options.filename:
            msg = "Options '-f/--file' and '-p/--policy' are mutually exclusive"
            raise WhynameAppError(msg, 2)
        elif options.policy:
            set_policy(options.policy, output_path)
            msg = "Policy seted OK"
        elif options.filename:
            r = open(options.filename, "r")
            set_policy(r.read(), output_path)
            r.close()
            msg = "Policy seted OK"
        else:
            msg = "%s:\n\t" % _HOSTNAME
            if os.path.isfile(output_path):
                r = open(output_path, "r")
                msg += "%s\n" % r.read()
                r.close()
            else:
                msg += "Policy not seted.\n"
    except Exception as err:
        print str(err)
        sys.exit(getattr(err, "code", 1000))
    else:
        print msg
    

